package com.heima.comment.service.impl;
import java.math.BigDecimal;

import com.heima.aliyun.GreenTextScan;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustException;
import com.heima.feigns.user.UserFeign;
import com.heima.model.comment.dtos.CommentRepayDto;
import com.heima.model.comment.dtos.CommentRepayLikeDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vos.ApCommentRepayVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppUserThreadLocalUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class CommentRepayServiceImpl implements CommentRepayService {

    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    GreenTextScan greenTextScan;
    @Autowired
    UserFeign userFeign;

    /**
     * 查看更多回复内容
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        //参数校验
        if (dto == null || StringUtils.isBlank(dto.getCommentId())) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getMinDate() == null) {
            dto.setMinDate(new Date());
        }
        if (dto.getSize() == null || dto.getSize() < 1) {
            dto.setSize(10);
        }
        //根据参数查询回复
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId())
                .and("createdTime").lt(dto.getMinDate()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                .limit(dto.getSize());
        List<ApCommentRepay> apCommentRepayList = mongoTemplate.find(query, ApCommentRepay.class);
        //判断是否存在回复数据
        if (apCommentRepayList == null || apCommentRepayList.size() == 0) {//没有直接返回空
            return ResponseResult.okResult();
        }
        //判断当前用户的登录状态
        ApUser user = AppUserThreadLocalUtils.getUser();
        if (user == null) {
            //用户未登录直接返回
            return ResponseResult.okResult(apCommentRepayList);
        }
        //查询回复中用户点赞过的
        ArrayList<ApCommentRepayVo> apCommentRepayVoList = new ArrayList<>();
        apCommentRepayList.stream().forEach(apCommentRepay -> {
            //创建返回给前端的vo对象
            ApCommentRepayVo apCommentRepayVo = new ApCommentRepayVo();
            BeanUtils.copyProperties(apCommentRepay, apCommentRepayVo);
            //判断当前回复用户是否点赞过
            ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(Query.query(Criteria.where("commentRepayId").is(apCommentRepay.getId())
                    .and("authorId").is(user.getId())), ApCommentRepayLike.class);
            if (apCommentRepayLike != null) {
                apCommentRepayVo.setOperation((short) 0);
            }
            apCommentRepayVoList.add(apCommentRepayVo);
        });
        return ResponseResult.okResult(apCommentRepayVoList);
    }

    /**
     * 保存回复
     *
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        //校验参数
        if (dto == null || StringUtils.isBlank(dto.getCommentId())) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //判断当前用户登录状态，只有登录用户才可以回复
        ApUser user = AppUserThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "请先登录再回复");
        }
        //验证回复内容文本
        if (StringUtils.isBlank(dto.getContent()) || dto.getContent().length() > 140) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE, "回复内容不能为空或者长度大于140");
        }
        try {
            Map resultMap = greenTextScan.greenTextScan(dto.getContent());
            if (!"pass".equals(resultMap.get("suggestion"))) {
                CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "回复内容阿里云文本审核失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "回复内容阿里云文本审核失败");
        }
        //远程调用方法查询用户姓名
        user = userFeign.findUserById(Long.valueOf(user.getId()));
        //封装参数插入数据
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(user.getId());
        apCommentRepay.setAuthorName(user.getName());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setLikes(0);
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        mongoTemplate.insert(apCommentRepay);
        //更新评论的回复数量
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        apComment.setReply(apComment.getReply()+1);
        mongoTemplate.save(apComment);
        //返回请求
        return ResponseResult.okResult();
    }

    /**
     * 点赞回复的评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDto dto) {
        //参数校验
        if(dto==null||dto.getCommentRepayId()==null||dto.getOperation()==null){
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //判断当前用户的登陆状态
        ApUser user = AppUserThreadLocalUtils.getUser();
        if(user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //获取当前回复
        ApCommentRepay apCommentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        Integer likes = apCommentRepay.getLikes();
        if(apCommentRepay==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"当前回复数据不存在");
        }
        //获取回复点赞对象
        Query query = Query.query(Criteria.where("commentRepayId").is(dto.getCommentRepayId())
                .and("authorId").is(user.getId()));
        ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(query, ApCommentRepayLike.class);
        //判断是点赞还是取消点赞
        if(dto.getOperation()==0){//点赞回复
            //判断是否点赞过
            if(apCommentRepayLike!=null){
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"已经点赞过该回复");
            }
            apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setAuthorId(user.getId());
            apCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());
            apCommentRepayLike.setOperation((short)0);
            //添加回复的点赞对象
            mongoTemplate.insert(apCommentRepayLike);
            ++likes;
        }else {//取消点赞回复
            //判断是否存在点赞对象
            if(apCommentRepayLike==null){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"已经取消了点赞该回复了");
            }
            mongoTemplate.remove(apCommentRepayLike);
            likes=likes>0?--likes:likes;
        }
        //修改回复点赞数量
        apCommentRepay.setLikes(likes);
        mongoTemplate.save(apCommentRepay);
        //封装点赞数量返回
        Map resultMap = new HashMap();
        resultMap.put("likes",likes);
        return ResponseResult.okResult(resultMap);
    }
}
